use actix_web::{web, App, HttpRequest, HttpServer, Responder};
use nats;
use std::net::{IpAddr};

#[macro_use]
extern crate lazy_static;

mod settings;

lazy_static! {
    static ref CONFIG: settings::Settings = 
        settings::Settings::new().expect("config can not be loaded");
}


async fn push_nats(_req: HttpRequest) -> impl Responder {
    println!("in push nats handler");
    let nats_link = format!("{}:{}", CONFIG.nats.host, CONFIG.nats.port);
    match nats::asynk::Options::with_token(&CONFIG.nats.token).connect(&nats_link).await {
        Ok(nc) => {
            match nc.publish(&CONFIG.gold_msg.subject, &CONFIG.gold_msg.message).await {
                Ok(_) => println!("successfully push to nats"),
                Err(e) => println!("push message fail {}", e)
            }
        },
        Err(e) => {
            println!("{}", e);
        }
    };
    format!("ksksjdjf") 

}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let ip = CONFIG.server.ip.parse::<IpAddr>().unwrap();
    HttpServer::new(|| {
        App::new()
        .route("/papergold", web::post().to(push_nats))
    })
    .bind((ip, CONFIG.server.port))?
    .run()
    .await
}

